package gold.digger;

import gold.utils.InputUtil;

import java.util.*;

/**
 * Created by fanzhenyu02 on 2021/12/10.
 * common problem solver template.
 */
public class LC1615 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {

        class Node {
            Set<Integer> linkRoads = new HashSet<>();
            Set<Integer> directConnectNode = new HashSet<>();
        }

        public int maximalNetworkRank(int n, int[][] roads) {
            if (roads.length <= 0) return 0;

            Node[] nodeLink = new Node[n];
            for (int i = 0; i < roads.length; i++) {
                int start = roads[i][0], end = roads[i][1];
                putRoad(nodeLink, start, end, i);
            }

            int ans = 0;
            for (int i = 0; i < n; i++) {
                for (int j = i + 1; j < n; j++) {
                    int curAns = getNodeLinkCnt(nodeLink, i) + getNodeLinkCnt(nodeLink, j) - (null != nodeLink[i] && nodeLink[i].directConnectNode.contains(j) ? 1 : 0);
                    ans = Math.max(ans, curAns);
                }
            }

            return ans;
        }

        public int getNodeLinkCnt(Node[] nodeLink, int i) {
            if (null == nodeLink[i]) return 0;
            return nodeLink[i].linkRoads.size();
        }

        public void putRoad(Node[] nodeLink, int startNode, int endNode, int curRoadIdx) {
            if (null == nodeLink[startNode]) nodeLink[startNode] = new Node();
            if (null == nodeLink[endNode]) nodeLink[endNode] = new Node();

            nodeLink[startNode].linkRoads.add(curRoadIdx);
            nodeLink[startNode].directConnectNode.add(endNode);

            nodeLink[endNode].linkRoads.add(curRoadIdx);
            nodeLink[endNode].directConnectNode.add(startNode);
        }
    }

    public void run() {
        Solution solution = new Solution();
//        System.out.println(solution.maximalNetworkRank(4, InputUtil.toDoubleIntegerArray("[[0,1],[0,3],[1,2],[1,3]]")));
//        System.out.println(solution.maximalNetworkRank(5, InputUtil.toDoubleIntegerArray("[[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]")));
//        System.out.println(solution.maximalNetworkRank(8, InputUtil.toDoubleIntegerArray("[[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]")));
        System.out.println(solution.maximalNetworkRank(6, InputUtil.toDoubleIntegerArray("[[2,4]]")));
//        System.out.println(solution.maximalNetworkRank(2, new int[][]{}));
    }

    public static void main(String[] args) throws Exception {
        LC1615 an = new LC1615();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
